package com.greedy.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.greedy.bean.pojo.Shop;
import com.greedy.constants.SystemConstants;
import com.greedy.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.n3r.eql.Eql;
import org.springframework.data.domain.Page;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.hutool.db.sql.SqlExecutor.query;
import static com.greedy.constants.CommentConstants.*;

/**
 * @Author: Yanxy
 * @Date: Created in:2022-12-25
 * Description: 商户信息
 */
@Slf4j
@Service
public class ShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 根据id查询商铺信息
     *
     * @param id 商铺id
     * @return 商铺详情数据
     */
    public Shop queryById(Long id) {
        // 缓存穿透
        Shop shop = queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 7.返回
        return shop;
    }

    /**
     * 根据商铺类型分页查询商铺信息
     *
     * @param typeId  商铺类型
     * @param current 页码
     * @param x       经纬度
     * @param y       经纬度
     * @return 商铺列表
     */
    public List<Shop> queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询，按数据库查询
            HashMap<String, Object> map = new HashMap<>(3);
            map.put("typeId", typeId);
            map.put("currentPage", (current - 1) * DEFAULT_PAGE_SIZE);
            map.put("pageSize", DEFAULT_PAGE_SIZE);
            List<Shop> shops = new Eql().select("getShopByTypeId").params(map).returnType(Shop.class).execute();
            log.info("大白点评-查询商铺信息-入参为：{},根据商铺类型分页信息：{}", JSON.toJSONString(map), JSON.toJSONString(shops));
            // 返回数据
            return shops;
        }
        // 2.计算分页参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;
        // 3.查询redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        // 单位:米
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        // 4.解析出id
        if (results == null) {
            return Collections.emptyList();
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Collections.emptyList();
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        String sql = "select * from shop where ID in(ids) ORDER BY FIELD(id, ids)";
        List<Shop> shops = new Eql().returnType(Shop.class).execute(sql.replaceAll("ids", idStr));
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return shops;
    }

    public List<Shop> queryShopByName(String name, Integer current) {
        // 根据类型分页查询
        HashMap<String, Object> map = new HashMap<>(3);
        map.put("name", name);
        map.put("currentPage", (current - 1) * MAX_PAGE_SIZE);
        map.put("pageSize", MAX_PAGE_SIZE);
        List<Shop> shops = new Eql().select("getShopByName").params(map).returnType(Shop.class).execute();
        log.info("大白点评-查询商铺信息-入参为：{},根据商铺类型分页信息：{}", JSON.toJSONString(map), JSON.toJSONString(shops));
        // 返回数据
        return shops;
    }

    /**
     * 根据指定的Key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透
     *
     * @param keyPrefix 缓存Key前缀
     * @param id        缓存Key后缀
     * @param type      系列化类型
     * @param time      缓存过期时间
     * @param unit      时间单位
     * @param <R>       实体类类型
     * @param <ID>      查库唯一标识
     * @return 查询对象信息
     */
    private <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Long time, TimeUnit unit) {
        // 组装Redis-key
        String key = keyPrefix + id;
        // 1、从Redis查询商铺缓存
        String cacheValue = stringRedisTemplate.opsForValue().get(key);
        // 2、判断是否存在
        if (StringUtils.isNotBlank(cacheValue)) {
            // 存在直接返回即可
            log.info("大白点评-查询商铺信息-入参为：{},根据id查询商铺缓存信息：{}", JSON.toJSONString(id), JSON.toJSONString(cacheValue));
            return JSON.parseObject(cacheValue, type);
        }
        // 3、判断命中的是否是空值
        if (cacheValue != null) {
            // 返回空，在方法调用后判断值为null的话抛异常或返回错误信息
            return null;
        }
        // 4、查库
        R dbValue = new Eql().selectFirst("getShopById").params(id).returnType(Shop.class).execute();
        // 4、库里也没有
        if (dbValue == null) {
            // 将空值写入Redis_失效2分钟
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回空，在方法调用后判断值为null的话抛异常或返回错误信息
            return null;
        }
        // 5、库里有
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(dbValue), time, unit);
        return dbValue;
    }

}
